from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import logging
from logging.handlers import RotatingFileHandler
from pathlib import Path

# 导入路由
from app.routes import main, quant, tools
from app.services.db import init_db

app = FastAPI(
    title="Tech Hub Portal",
    description="个人技术门户与量化中枢",
    version="1.0.0"
)

# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 挂载静态文件
app.mount("/static", StaticFiles(directory="app/static"), name="static")

# 注册路由
app.include_router(main.router, tags=["main"])
app.include_router(quant.router, prefix="/api/quant", tags=["quant"])
app.include_router(tools.router, prefix="/api/tools", tags=["tools"])

@app.on_event("startup")
async def startup_event():
    """应用启动时执行"""
    log_dir = Path("app/static/logs")
    log_dir.mkdir(parents=True, exist_ok=True)
    handler = RotatingFileHandler(str(log_dir / "app.log"), maxBytes=2 * 1024 * 1024, backupCount=5, encoding="utf-8")
    fmt = logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s")
    handler.setFormatter(fmt)
    root = logging.getLogger()
    root.setLevel(logging.INFO)
    if not any(isinstance(h, RotatingFileHandler) for h in root.handlers):
        root.addHandler(handler)
    init_db()
    print("🚀 Tech Hub Portal 启动成功!")

@app.on_event("shutdown") 
async def shutdown_event():
    """应用关闭时执行"""
    print("👋 Tech Hub Portal 已关闭")